package com.ztools.wx.core;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.ztools.common.util.common.Result;
import com.ztools.common.util.common.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

import static com.ztools.wx.config.WxSysConstants.COOKIE_OPENID;

/**
 * @Author:seeTools
 * @Date: 2023/4/9  15:54
 * @Version 1.0
 */
@Component
public class OpenIdAuthorizationInterceptor extends HandlerInterceptorAdapter {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        OpenIdAuthorization openIdAuthorization = method.getAnnotation(OpenIdAuthorization.class);
        if (openIdAuthorization != null) {
            // 获取header
            String openId = "";
            //判断cookie中是否存在openid，存在则直接返回，不存在则先获取再存进cookie
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (COOKIE_OPENID.equals(cookie.getName())) {
                        openId = cookie.getValue();
                        break;
                    }
                }
            }
            if (StrUtil.isNotEmpty(openId)) {
                // 判断该header是否合法
                return true;
            }
            sendMessage(response, ResultCode.LEGAL);
            return false;
        }
        return true;
    }


    private void sendMessage(HttpServletResponse response, ResultCode resultCode) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.setStatus(200);
        try {
            response.getWriter().write(JSON.toJSONString(Result.error(resultCode)));
        } catch (IOException ex) {
            logger.error(ex.getMessage());
        }
    }

}
